package com.aliang.shopping.controller;

import com.aliang.shopping.common.Result;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.contact.ResultMsgContact;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.model.dto.goods.GoodsEsDto;
import com.aliang.shopping.model.po.UserCollect;
import com.aliang.shopping.security.PreventRepeatSubmit;
import com.aliang.shopping.security.auth.UserHolder;
import com.aliang.shopping.service.GoodsService;
import com.aliang.shopping.service.UserCollectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userCollect")
@AllArgsConstructor
public class UserCollectController {

    private final UserCollectService userCollectService;
    private final GoodsService goodsService;

    /**
     * 用户收藏
     *
     * @param goodsId 商品Id
     * @return
     */
    @PostMapping("/insert/{goodsId}")
    @ApiOperation("用户收藏")
    @PreventRepeatSubmit
    public Result<String> insertUserCollect(@PathVariable Long goodsId) {
        //获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        //判断该用户是否已收藏
        int count = this.userCollectService.count(new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, userId)
                .eq(UserCollect::getGoodsId, goodsId)
        );
        if (count > 0) {
            //已添加，抛出提示已收藏
            throw new DataException(ResultCodeEnum.USER_COLLECT_EXIST);
        }
        //封装用户收藏对象
        UserCollect userCollect = new UserCollect();
        userCollect.setGoodsId(goodsId);
        userCollect.setUserId(userId);
        //插入数据
        boolean b = this.userCollectService.save(userCollect);
        //返回结果
        return b ? Result.ok(ResultMsgContact.INSERT_SUCCESS) : Result.fail(ResultMsgContact.INSERT_FAIL);
    }

    /**
     * 用户收藏删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/del")
    @ApiOperation("用户收藏删除")
    @PreventRepeatSubmit
    public Result<String> delUserCollect(@RequestBody List<Long> ids) {
        // 获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        // 根据用户Id和商品Id删除数据
        boolean remove = this.userCollectService.remove(new LambdaQueryWrapper<UserCollect>()
                .in(UserCollect::getUserId, userId)
                .in(UserCollect::getGoodsId, ids)

        );
        return remove ? Result.ok(ResultMsgContact.DELETE_SUCCESS) : Result.fail(ResultMsgContact.DELETE_FAIL);
    }

    /**
     * 查询用户是否收藏
     */
    @DeleteMapping("/collect_flag/{goodsId}")
    @ApiOperation("查询用户是否收藏")
    @PreventRepeatSubmit
    public Result<Boolean> getCollectFlag(@PathVariable Long goodsId) {
        // 获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        // 根据用户Id和商品Id查询用户是否收藏该商品
        int count = this.userCollectService.count(
                new LambdaQueryWrapper<UserCollect>()
                        .eq(UserCollect::getUserId, userId)
                        .eq(UserCollect::getGoodsId, goodsId)
        );

        return Result.ok(count > 0);
    }


    /**
     * 获取用户全部收藏信息
     */
    @GetMapping("/getUserCollectList")
    @ApiOperation("获取用户全部收藏信息")
    public Result<List<GoodsEsDto>> getUserCollectList() {
        //获取登录用户Id
        Long userId = UserHolder.getUserId();
        //根据用户Id查询用户收藏列表，排序升序，更新时间倒序
        List<UserCollect> list = this.userCollectService.list(
                new LambdaQueryWrapper<UserCollect>()
                        .select(UserCollect::getGoodsId)
                        .eq(UserCollect::getUserId, userId)
                        .orderByAsc(UserCollect::getUpdateTime)
                        .orderByAsc(UserCollect::getCreateTime)
        );
        //没有数据，返回空集合
        if (list.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //获取商品Id
        List<Long> goodsIds = list.stream().map(UserCollect::getGoodsId).collect(Collectors.toList());
        // 从ES中获取商品信息
        List<GoodsEsDto> goodsList = this.goodsService.getListWithEs(goodsIds);
        //返回数据
        return Result.ok(goodsList);
    }
}
